

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="参考资料：Java语言程序设计（进阶篇） ——梁勇先生 著 戴开宇先生 译@[toc] 运行环境  Windows10 JDK8 IDEA  前言 有一天大雄惊讶地看着自己零分的考卷… 哆啦A梦说：”大雄，你怎么又考了个零分呀！ 大雄：”什么嘛，哆啦A梦，因为考的题太难了！我不会呀” 然后…… 哆啦A梦随着大雄来到学校进行了一场考试 结果是：    名字 成绩    大雄 0   哆啦A梦 100">
<meta property="og:type" content="article">
<meta property="og:title" content="Java集合系列1_ PriorityQueue优先队列 _ 综合运用 _ 深入理解">
<meta property="og:url" content="http://example.com/2021/11/22/Java%E9%9B%86%E5%90%88%E7%B3%BB%E5%88%97%EF%BC%88%E4%B8%80%EF%BC%89_%20PriorityQueue%E4%BC%98%E5%85%88%E9%98%9F%E5%88%97%20_%20%E7%BB%BC%E5%90%88%E8%BF%90%E7%94%A8%20_%20%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="参考资料：Java语言程序设计（进阶篇） ——梁勇先生 著 戴开宇先生 译@[toc] 运行环境  Windows10 JDK8 IDEA  前言 有一天大雄惊讶地看着自己零分的考卷… 哆啦A梦说：”大雄，你怎么又考了个零分呀！ 大雄：”什么嘛，哆啦A梦，因为考的题太难了！我不会呀” 然后…… 哆啦A梦随着大雄来到学校进行了一场考试 结果是：    名字 成绩    大雄 0   哆啦A梦 100">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/ff68968610004ee2a4b5a540ac2b5fcf.jpg#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/438391e1c75d44c69c777922fda25546.jpg#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/a75308d94b9446138775a2c20b252361.jpg#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/438391e1c75d44c69c777922fda25546.jpg#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/bea7b43a0c0840b79d73d72532877d5a.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/350de9c7801f49a2aace609c4f1b3772.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/11c06ea488e2470da5e14719553666ab.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/e8e3f20ed3c24aaeb2324441b5b19a45.png">
<meta property="og:image" content="https://img-blog.csdnimg.cn/5af11f02ba3844abae40d193d5e8eefc.png">
<meta property="article:published_time" content="2021-11-22T12:29:35.000Z">
<meta property="article:modified_time" content="2022-08-22T15:45:16.191Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/ff68968610004ee2a4b5a540ac2b5fcf.jpg#pic_center">
  
  
  
  <title>Java集合系列1_ PriorityQueue优先队列 _ 综合运用 _ 深入理解 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Java集合系列1_ PriorityQueue优先队列 _ 综合运用 _ 深入理解"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2021-11-22 20:29" pubdate>
          2021年11月22日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          9.3k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          78 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Java集合系列1_ PriorityQueue优先队列 _ 综合运用 _ 深入理解</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>参考资料：Java语言程序设计（进阶篇） ——梁勇先生 著 戴开宇先生 译<br>@[toc]</p>
<h1 id="运行环境"><a href="#运行环境" class="headerlink" title="运行环境"></a>运行环境</h1><hr>
<ul>
<li>Windows10</li>
<li>JDK8</li>
<li>IDEA</li>
</ul>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><hr>
<p>有一天<br><img src="https://img-blog.csdnimg.cn/ff68968610004ee2a4b5a540ac2b5fcf.jpg#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>大雄惊讶地看着自己零分的考卷…</p>
<p><img src="https://img-blog.csdnimg.cn/438391e1c75d44c69c777922fda25546.jpg#pic_center" srcset="/img/loading.gif" lazyload><br>哆啦A梦说：”大雄，你怎么又考了个零分呀！</p>
<p><img src="https://img-blog.csdnimg.cn/a75308d94b9446138775a2c20b252361.jpg#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>大雄：”什么嘛，哆啦A梦，因为考的题太难了！我不会呀”</p>
<p>然后……</p>
<p>哆啦A梦随着大雄来到学校进行了一场考试</p>
<p>结果是：</p>
<table>
<thead>
<tr>
<th>名字</th>
<th>成绩</th>
</tr>
</thead>
<tbody><tr>
<td>大雄</td>
<td>0</td>
</tr>
<tr>
<td>哆啦A梦</td>
<td>100</td>
</tr>
<tr>
<td>静香</td>
<td>96</td>
</tr>
<tr>
<td>胖虎</td>
<td>60</td>
</tr>
<tr>
<td>小夫</td>
<td>90</td>
</tr>
</tbody></table>
<p>哆啦A梦：哎，不愧是大雄，又是零分，咦？ 怎么成绩没有排序啊？</p>
<p><img src="https://img-blog.csdnimg.cn/438391e1c75d44c69c777922fda25546.jpg#pic_center" srcset="/img/loading.gif" lazyload><br>哆啦A梦：接下来，就让我掏出一个宝贝来解决把！当当当当，$Priority Queue优先队列$ ！接下来，先创建一个实体类 $Student.java$来表示大雄他们吧~</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Student</span>&#123;<br>    <span class="hljs-keyword">private</span> String id;<br>    <span class="hljs-keyword">private</span> Character gender;<br>    <span class="hljs-keyword">private</span> Double score;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">Student</span><span class="hljs-params">(String id, Character gender, Double score)</span> &#123;<br>        <span class="hljs-built_in">this</span>.id = id;<br>        <span class="hljs-built_in">this</span>.gender = gender;<br>        <span class="hljs-built_in">this</span>.score = score;<br>    &#125;<br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">getId</span><span class="hljs-params">()</span> &#123;  <span class="hljs-keyword">return</span> id; &#125;<br>    <span class="hljs-keyword">public</span> Character <span class="hljs-title function_">getGender</span><span class="hljs-params">()</span> &#123; <span class="hljs-keyword">return</span> gender;&#125;<br>    <span class="hljs-keyword">public</span> Double <span class="hljs-title function_">getScore</span><span class="hljs-params">()</span> &#123;<span class="hljs-keyword">return</span> score; &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">toString</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Student&#123;&quot;</span> +<br>                <span class="hljs-string">&quot;id=&#x27;&quot;</span> + id + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +<br>                <span class="hljs-string">&quot;, gender=&quot;</span> + gender +<br>                <span class="hljs-string">&quot;, score=&quot;</span> + score +<br>                <span class="hljs-string">&#x27;&#125;&#x27;</span>;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<h1 id="1-队列与优先队列概述"><a href="#1-队列与优先队列概述" class="headerlink" title="1. 队列与优先队列概述"></a>1. 队列与优先队列概述</h1><hr>
<p><strong>队列</strong> $queue$ 是一种 $FIFO$ 即先进先出的数据结构，元素被追加到队列末尾，然后从队列头删除。</p>
<p><strong>优先队列</strong> $Priority Queue$ 是 在 $queue$ 的基础上给每个队列元素提供了一个优先级来进行比较</p>
<p>本篇文章，有许多关于比较器 $Comparator$ 的知识，若需要了解，除了在网络上查询资料外，可以参考这篇博文：<br><a target="_blank" rel="noopener" href="https://blog.csdn.net/Unirithe/article/details/121450534">【Java进阶】Comparable接口与Comparator接口的深入理解 | 有关排序的都会用到</a></p>
<h1 id="2-优先队列结构剖析"><a href="#2-优先队列结构剖析" class="headerlink" title="2. 优先队列结构剖析"></a>2. 优先队列结构剖析</h1><hr>
<h2 id="2-1-集合框架中的优先队列"><a href="#2-1-集合框架中的优先队列" class="headerlink" title="2.1 集合框架中的优先队列"></a>2.1 集合框架中的优先队列</h2><p><code>PriorityQueue的UML图</code>  制作工具: IDEA<br><img src="https://img-blog.csdnimg.cn/bea7b43a0c0840b79d73d72532877d5a.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>从图中可以看出</p>
<ul>
<li><p>优先队列实现了 $Serializable$ 接口，所以是可序列化的。</p>
</li>
<li><p>继承了$AbstractQueue$ 类 ，这个类实现了 $Iterable$ 接口的间接子接口$Queue$，所以优先队列是可迭代的。故可通过 $foreach$ 语句循环遍历（<code>注: 输出的结果无序的</code>）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java">PriorityQueue&lt;String&gt; pq = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PriorityQueue</span>&lt;&gt;();<br><br><span class="hljs-keyword">for</span>(String s : pq)&#123;<br>	<span class="hljs-comment">// System.out.println(s);</span><br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="2-2-成员变量"><a href="#2-2-成员变量" class="headerlink" title="2.2 成员变量"></a>2.2 成员变量</h2><p>成员变量除了自身的成员变量，其内部类中也有成员变量</p>
<p>可以通过下面的UML图进行了解：</p>
<p><img src="https://img-blog.csdnimg.cn/350de9c7801f49a2aace609c4f1b3772.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h2 id="2-2-常用方法"><a href="#2-2-常用方法" class="headerlink" title="2.2 常用方法"></a>2.2 常用方法</h2><hr>
<p>Java集合框架的方法有许多，而且有些方法是来自于接口，有的是本身独有的方法，非常繁杂，笔者认为没有必要记住所有的使用方法，最主要的是 </p>
<ul>
<li><p>记住所有的构造方法 ，方便创建对象 </p>
</li>
<li><p>记住常用的方法，比如在队列中的peek() 、poll()、add()、offer()、remove() 等</p>
</li>
</ul>
<h3 id="2-2-1-构造器"><a href="#2-2-1-构造器" class="headerlink" title="2.2.1 构造器"></a>2.2.1 构造器</h3><p><img src="https://img-blog.csdnimg.cn/11c06ea488e2470da5e14719553666ab.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br>优先队列构造器用到的主要对象有：</p>
<ul>
<li>$Comparator$ 比较器，通过调用比较器的compare方法赋予元素优先级</li>
<li>$int$  ，整型变量表示优先队列的容量</li>
<li>$Collection$ 集合容器接口的实现类，这里并不表示接纳所有的集合类，具体得查看源码，之后会进行分析</li>
<li>$SortedSet$ 有序集合接口的实现类</li>
</ul>
<p>最后一个可排序的集合有什么用呢？在成员变量中没有看到该类型，这说明肯定是在构造函数中调用了其他方法对该对象进行了类型变换，后经查询资料发现：</p>
<ul>
<li>PriorityQueue内部实现是采用 <code>堆排序</code></li>
</ul>
<p>接下来，先编写一个函数运用反射机制用于输出一个类的所有的成员变量，包括私有成员，这样方便查看不同构造器下的差异。<br>用到的包</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.lang.reflect.Field;<br><span class="hljs-keyword">import</span> java.util.PriorityQueue;<br></code></pre></td></tr></table></figure>

<p><code>printPriority() </code>方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> &lt;T&gt; <span class="hljs-keyword">void</span> <span class="hljs-title function_">printPriority</span><span class="hljs-params">(PriorityQueue&lt;T&gt; q)</span> &#123;<br>    <span class="hljs-comment">// 反射机制获取类的内容</span><br>    Field[] info = q.getClass().getDeclaredFields();        <br>    <span class="hljs-keyword">for</span> (Field field : info) &#123;<br>        <span class="hljs-comment">// 打开所有访问权限</span><br>        field.setAccessible(<span class="hljs-literal">true</span>);      <br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">//格式化输出</span><br>            System.out.println(<br>                    String.format(<span class="hljs-string">&quot;Type:%-30s Name: %-25s Value:%-10s&quot;</span>,<br>                            field.getType(),<br>                            field.getName(),<br>                            field.get(q))); <br>        &#125; <span class="hljs-keyword">catch</span> (IllegalAccessException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>(1) 无参构造  new PriorityQueue&lt;&gt;()</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Demo</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        PriorityQueue&lt;Student&gt; q = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PriorityQueue</span>&lt;&gt;();<br>        printPriority(q);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>运行结果</p>
</blockquote>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs pgsql"><span class="hljs-keyword">Type</span>:long                           <span class="hljs-type">Name</span>: serialVersionUID          <span class="hljs-keyword">Value</span>:<span class="hljs-number">-7720805057305804111</span><br><span class="hljs-keyword">Type</span>:<span class="hljs-type">int</span>                            <span class="hljs-type">Name</span>: DEFAULT_INITIAL_CAPACITY  <span class="hljs-keyword">Value</span>:<span class="hljs-number">11</span>        <br><span class="hljs-keyword">Type</span>:<span class="hljs-keyword">class</span> [Ljava.lang.<span class="hljs-keyword">Object</span>;      <span class="hljs-type">Name</span>: queue                     <span class="hljs-keyword">Value</span>:[Ljava.lang.<span class="hljs-keyword">Object</span>;@<span class="hljs-number">12</span>a3a380<br><span class="hljs-keyword">Type</span>:<span class="hljs-type">int</span>                            <span class="hljs-type">Name</span>: size                      <span class="hljs-keyword">Value</span>:<span class="hljs-number">0</span>         <br><span class="hljs-keyword">Type</span>:interface java.util.Comparator <span class="hljs-type">Name</span>: comparator                <span class="hljs-keyword">Value</span>:<span class="hljs-keyword">null</span>      <br><span class="hljs-keyword">Type</span>:<span class="hljs-type">int</span>                            <span class="hljs-type">Name</span>: modCount                  <span class="hljs-keyword">Value</span>:<span class="hljs-number">0</span>         <br><span class="hljs-keyword">Type</span>:<span class="hljs-type">int</span>                            <span class="hljs-type">Name</span>: MAX_ARRAY_SIZE            <span class="hljs-keyword">Value</span>:<span class="hljs-number">2147483639</span><br></code></pre></td></tr></table></figure>

<p>(2) 传入容量参数 new PriorityQueue&lt;&gt;(int initialCapacity)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Demo</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        PriorityQueue&lt;Student&gt; q = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PriorityQueue</span>&lt;&gt;(<span class="hljs-number">100</span>);<br>        printPriority(q);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>运行结果</p>
</blockquote>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs pgsql"><span class="hljs-keyword">Type</span>:long                           <span class="hljs-type">Name</span>: serialVersionUID          <span class="hljs-keyword">Value</span>:<span class="hljs-number">-7720805057305804111</span><br><span class="hljs-keyword">Type</span>:<span class="hljs-type">int</span>                            <span class="hljs-type">Name</span>: DEFAULT_INITIAL_CAPACITY  <span class="hljs-keyword">Value</span>:<span class="hljs-number">11</span>        <br><span class="hljs-keyword">Type</span>:<span class="hljs-keyword">class</span> [Ljava.lang.<span class="hljs-keyword">Object</span>;      <span class="hljs-type">Name</span>: queue                     <span class="hljs-keyword">Value</span>:[Ljava.lang.<span class="hljs-keyword">Object</span>;@<span class="hljs-number">12</span>a3a380<br><span class="hljs-keyword">Type</span>:<span class="hljs-type">int</span>                            <span class="hljs-type">Name</span>: size                      <span class="hljs-keyword">Value</span>:<span class="hljs-number">0</span>         <br><span class="hljs-keyword">Type</span>:interface java.util.Comparator <span class="hljs-type">Name</span>: comparator                <span class="hljs-keyword">Value</span>:<span class="hljs-keyword">null</span>      <br><span class="hljs-keyword">Type</span>:<span class="hljs-type">int</span>                            <span class="hljs-type">Name</span>: modCount                  <span class="hljs-keyword">Value</span>:<span class="hljs-number">0</span>         <br><span class="hljs-keyword">Type</span>:<span class="hljs-type">int</span>                            <span class="hljs-type">Name</span>: MAX_ARRAY_SIZE            <span class="hljs-keyword">Value</span>:<span class="hljs-number">2147483639</span><br></code></pre></td></tr></table></figure>

<p>观察结果可以发现，优先队列本身size的值不会因此发生变化，因为它表示当前的元素个数</p>
<p>初始化时，实际变化的是其成员<code>queue</code>的容量，在源码中是这样实现的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-built_in">this</span>.queue = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Object</span>[initialCapacity];<br></code></pre></td></tr></table></figure>

<p>(3) 传入比较器, 使用匿名内部类实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Demo</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        PriorityQueue&lt;Student&gt; q = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PriorityQueue</span>&lt;&gt;(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Comparator</span>&lt;Student&gt;() &#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">compare</span><span class="hljs-params">(Student o1, Student o2)</span> &#123;<br>                <span class="hljs-keyword">return</span> o1.getScore() - o2.getScore() &gt; <span class="hljs-number">0</span> ? <span class="hljs-number">1</span> : -<span class="hljs-number">1</span>;<br>            &#125;<br>        &#125;);<br>        printPriority(q);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>运行结果</p>
</blockquote>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs less">Type:long                           Name: serialVersionUID          Value:-7720805057305804111<br>Type:int                            Name: DEFAULT_INITIAL_CAPACITY  Value:11        <br>Type:class [Ljava.lang.Object;      Name: queue                     Value:[Ljava.lang.Object;<span class="hljs-variable">@12a3a380</span><br><span class="hljs-attribute">Type</span>:int                            <span class="hljs-attribute">Name</span>: size                      <span class="hljs-attribute">Value</span>:<span class="hljs-number">0</span>         <br><span class="hljs-attribute">Type</span>:interface java.util.Comparator <span class="hljs-attribute">Name</span>: comparator                <span class="hljs-attribute">Value</span>:Demo$<span class="hljs-number">1</span><span class="hljs-variable">@29453f44</span><br><span class="hljs-attribute">Type</span>:int                            <span class="hljs-attribute">Name</span>: modCount                  <span class="hljs-attribute">Value</span>:<span class="hljs-number">0</span>         <br><span class="hljs-attribute">Type</span>:int                            <span class="hljs-attribute">Name</span>: MAX_ARRAY_SIZE            <span class="hljs-attribute">Value</span>:<span class="hljs-number">2147483639</span><br></code></pre></td></tr></table></figure>

<p>可以观察到优先队列中的<code>comparator</code> 变量发生了变化，从而定义优先队列元素的优先级</p>
<p>对于其他的方法，部分是来自于父类 <code>AbstracQueue</code> 和父类实现的接口 <code>Queue</code><br><img src="https://img-blog.csdnimg.cn/e8e3f20ed3c24aaeb2324441b5b19a45.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><img src="https://img-blog.csdnimg.cn/5af11f02ba3844abae40d193d5e8eefc.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h3 id="2-2-2-添加元素-入队-add方法-offer方法"><a href="#2-2-2-添加元素-入队-add方法-offer方法" class="headerlink" title="2.2.2 添加元素 | 入队 |  add方法 | offer方法"></a>2.2.2 添加元素 | 入队 |  add方法 | offer方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">add</span><span class="hljs-params">(E e)</span>&#123;&#125;<br><span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">offer</span><span class="hljs-params">(E e)</span> &#123;&#125;<br></code></pre></td></tr></table></figure>
<p>优先队列 <code>PriorityQueue</code> 继承了 <code>AbstractQueue</code> 类，实现了<code>Queue</code>接口。</p>
<p>这两个方法都是在<code>Queue</code>接口中声明的，抽象类实现了其中的 <code>add() </code>方法</p>
<p>在优先队列源码中，add()方法的原理就是调用自身实现的<code>offer() </code>方法</p>
<p>它们的区别在于：</p>
<ul>
<li>offer()  方法 会抛出异常</li>
</ul>
<p>在源码中，<code>Queue</code>接口的 offer() 方法 规定 若参数为null则抛出一个异常</p>
<h3 id="2-2-3-删除元素-出队-remove方法-poll-方法"><a href="#2-2-3-删除元素-出队-remove方法-poll-方法" class="headerlink" title="2.2.3 删除元素 | 出队 | remove方法 | poll 方法"></a>2.2.3 删除元素 | 出队 | remove方法 | poll 方法</h3><p>在队列中， remove(Object o) 方法执行时，若o&#x3D;&#x3D;null，则会报错，但在优先队列里并没有这个规定</p>
<p>通过查看源码，队列的另一个<code>java.util.LinkedList</code>实现类中的remove方法才会在空值时抛出异常</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">remove</span><span class="hljs-params">(Object o)</span> &#123;&#125;<br><span class="hljs-keyword">public</span> E <span class="hljs-title function_">poll</span><span class="hljs-params">()</span> &#123;&#125;<br></code></pre></td></tr></table></figure>

<h1 id="3-遍历优先队列的三种方式"><a href="#3-遍历优先队列的三种方式" class="headerlink" title="3. 遍历优先队列的三种方式"></a>3. 遍历优先队列的三种方式</h1><hr>
<p>遍历前，先插入测试的数据：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><br>q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;大雄&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">0.0</span>));<br>q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;哆啦A梦&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">100.0</span>));<br>q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;静香&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">96.0</span>));<br>q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;胖虎&quot;</span>, <span class="hljs-string">&#x27;W&#x27;</span>, <span class="hljs-number">60.0</span>));<br>q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;小夫&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">90.0</span>));<br></code></pre></td></tr></table></figure>
<h2 id="3-1-直接For循环遍历-无序"><a href="#3-1-直接For循环遍历-无序" class="headerlink" title="3.1 直接For循环遍历 (无序)"></a>3.1 直接For循环遍历 (无序)</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">for</span> (Student student : q) &#123;<br>	System.out.println(student);<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="3-2-出队方式遍历-有序"><a href="#3-2-出队方式遍历-有序" class="headerlink" title="3.2 出队方式遍历 (有序)"></a>3.2 出队方式遍历 (有序)</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">PriorityQueue&lt;Student&gt; temp = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PriorityQueue</span>&lt;&gt;(q);<br><span class="hljs-keyword">while</span>(!temp.isEmpty())&#123;<br>    System.out.println(temp.poll());<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="3-3-迭代器遍历-无序"><a href="#3-3-迭代器遍历-无序" class="headerlink" title="3.3 迭代器遍历 (无序)"></a>3.3 迭代器遍历 (无序)</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">Iterator&lt;Student&gt; iterator = temp.iterator();<br><span class="hljs-keyword">while</span>(iterator.hasNext()) &#123;<br>	System.out.println(iterator.next());<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="3-4-toArray方法遍历-无序"><a href="#3-4-toArray方法遍历-无序" class="headerlink" title="3.4 toArray方法遍历 (无序)"></a>3.4 toArray方法遍历 (无序)</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">Object[] students = (Object[]) q.toArray();<br><span class="hljs-keyword">for</span> (Object student : students) &#123;<br>     System.out.println(student);<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="3-5-反射机制遍历（无序）-少用"><a href="#3-5-反射机制遍历（无序）-少用" class="headerlink" title="3.5 反射机制遍历（无序） (少用)"></a>3.5 反射机制遍历（无序） (少用)</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">try</span> &#123;<br>    <span class="hljs-type">Field</span> <span class="hljs-variable">field</span> <span class="hljs-operator">=</span> q.getClass().getDeclaredField(<span class="hljs-string">&quot;queue&quot;</span>);<br>    field.setAccessible(<span class="hljs-literal">true</span>);<br>    Object []obj = (Object[]) (field.get(q));<br>    <span class="hljs-keyword">for</span> (Object o : obj) &#123;<br>         System.out.println(o);<br>    &#125;<br>&#125; <span class="hljs-keyword">catch</span> (NoSuchFieldException e) &#123;<br>     e.printStackTrace();<br>&#125; <span class="hljs-keyword">catch</span> (IllegalAccessException e) &#123;<br>     e.printStackTrace();<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="4-优先队列的自动化排序机制"><a href="#4-优先队列的自动化排序机制" class="headerlink" title="4. 优先队列的自动化排序机制"></a>4. 优先队列的自动化排序机制</h1><hr>
<h2 id="4-1-单一排序-升序"><a href="#4-1-单一排序-升序" class="headerlink" title="4.1 单一排序 升序"></a>4.1 单一排序 升序</h2><p>单一排序是指仅仅以一个参数作为标准来进行比较，当创建优先队列的对象没有指定比较器时，如果是可比较的类型（String、int等），那么队列会默认以升序进行排列，比如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java">PriorityQueue&lt;Integer&gt; q2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PriorityQueue</span>&lt;&gt;();<br>q2.add(<span class="hljs-number">1</span>);<br>q2.add(<span class="hljs-number">3</span>);<br>q2.add(<span class="hljs-number">2</span>);<br><span class="hljs-keyword">while</span>(!q2.isEmpty())<br>	System.out.println(q2.poll());<br></code></pre></td></tr></table></figure>
<blockquote>
<p>运行结果</p>
</blockquote>
<blockquote>
<p>1<br>2<br>3</p>
</blockquote>
<p>自定义类的<strong>比较器实现</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>    PriorityQueue&lt;Student&gt; q = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PriorityQueue</span>&lt;&gt;(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Comparator</span>&lt;Student&gt;() &#123;<br>        <span class="hljs-meta">@Override</span><br>        <span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">compare</span><span class="hljs-params">(Student o1, Student o2)</span> &#123;<br>            <span class="hljs-keyword">return</span> o1.getScore() - o2.getScore() &gt; <span class="hljs-number">0</span> ? <span class="hljs-number">1</span> : -<span class="hljs-number">1</span>;<br>        &#125;<br>    &#125;);<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;大雄&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">0.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;哆啦A梦&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">100.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;静香&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">96.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;胖虎&quot;</span>, <span class="hljs-string">&#x27;W&#x27;</span>, <span class="hljs-number">60.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;小夫&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">90.0</span>));<br><br>    <span class="hljs-keyword">while</span>(!q.isEmpty())<br>        System.out.println(q.poll());<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>运行结果</p>
</blockquote>
<blockquote>
<p>Student{id&#x3D;’大雄’, gender&#x3D;M, score&#x3D;0.0}<br>Student{id&#x3D;’胖虎’, gender&#x3D;W, score&#x3D;60.0}<br>Student{id&#x3D;’小夫’, gender&#x3D;M, score&#x3D;90.0}<br>Student{id&#x3D;’静香’, gender&#x3D;M, score&#x3D;96.0}<br>Student{id&#x3D;’哆啦A梦’, gender&#x3D;M, score&#x3D;100.0}</p>
</blockquote>
<h2 id="4-2-单一排序-降序"><a href="#4-2-单一排序-降序" class="headerlink" title="4.2 单一排序 降序"></a>4.2 单一排序 降序</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>    PriorityQueue&lt;Integer&gt; q2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PriorityQueue</span>&lt;&gt;(Collections.reverseOrder());<br>    q2.add(<span class="hljs-number">1</span>);<br>    q2.add(<span class="hljs-number">3</span>);<br>    q2.add(<span class="hljs-number">2</span>);<br>    <span class="hljs-keyword">while</span>(!q2.isEmpty())<br>        System.out.println(q2.poll());<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>运行结果</p>
</blockquote>
<blockquote>
<p>3<br>2<br>1</p>
</blockquote>
<p><strong>自定义类 比较器</strong></p>
<p>这里其实不用调用 <code>Collections.reverseOrder()</code> 方法，直接修改compare的返回值也是可以的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>    PriorityQueue&lt;Student&gt; q = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PriorityQueue</span>&lt;&gt;(Collections.reverseOrder(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Comparator</span>&lt;Student&gt;() &#123;<br>        <span class="hljs-meta">@Override</span><br>        <span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">compare</span><span class="hljs-params">(Student o1, Student o2)</span> &#123;<br>            <span class="hljs-keyword">return</span> o1.getScore() - o2.getScore() &gt; <span class="hljs-number">0</span> ? <span class="hljs-number">1</span> : -<span class="hljs-number">1</span>;<br>        &#125;<br>    &#125;));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;大雄&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">0.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;哆啦A梦&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">100.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;静香&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">96.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;胖虎&quot;</span>, <span class="hljs-string">&#x27;W&#x27;</span>, <span class="hljs-number">60.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;小夫&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">90.0</span>));<br>    <span class="hljs-keyword">while</span> (!q.isEmpty())<br>        System.out.println(q.poll());<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="4-3-综合排序"><a href="#4-3-综合排序" class="headerlink" title="4.3 综合排序"></a>4.3 综合排序</h2><p>假设 “ 女士优先 “ ，先把女孩子都排在前面，然后再根据成绩排序，实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>    PriorityQueue&lt;Student&gt; q = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PriorityQueue</span>&lt;&gt;(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Comparator</span>&lt;Student&gt;() &#123;<br>        <span class="hljs-meta">@Override</span><br>        <span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">compare</span><span class="hljs-params">(Student o1, Student o2)</span> &#123;<br>            <span class="hljs-keyword">if</span>(!o1.getGender().equals(o2.getGender()))<br>                <span class="hljs-keyword">return</span> o1.getGender().equals(<span class="hljs-string">&#x27;W&#x27;</span>) ? -<span class="hljs-number">1</span> : <span class="hljs-number">1</span>;<br>            <span class="hljs-keyword">else</span><br>                <span class="hljs-keyword">return</span> o1.getScore() - o2.getScore() &gt; <span class="hljs-number">0</span> ? -<span class="hljs-number">1</span> : <span class="hljs-number">1</span>;<br>        &#125;<br>    &#125;);<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;大雄&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">0.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;哆啦A梦&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">100.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;静香&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">96.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;胖虎&quot;</span>, <span class="hljs-string">&#x27;W&#x27;</span>, <span class="hljs-number">60.0</span>));<br>    q.offer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Student</span>(<span class="hljs-string">&quot;小夫&quot;</span>, <span class="hljs-string">&#x27;M&#x27;</span>, <span class="hljs-number">90.0</span>));<br>    <span class="hljs-keyword">while</span> (!q.isEmpty())<br>        System.out.println(q.poll());<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>运行结果</p>
</blockquote>
<blockquote>
<p>Student{id&#x3D;’胖虎’, gender&#x3D;W, score&#x3D;60.0}<br>Student{id&#x3D;’哆啦A梦’, gender&#x3D;M, score&#x3D;100.0}<br>Student{id&#x3D;’静香’, gender&#x3D;M, score&#x3D;96.0}<br>Student{id&#x3D;’小夫’, gender&#x3D;M, score&#x3D;90.0}<br>Student{id&#x3D;’大雄’, gender&#x3D;M, score&#x3D;0.0}</p>
</blockquote>
<p>emmmm，笔者不小心把胖虎性别弄成女孩了，问题不大…</p>
<h1 id="5-总结"><a href="#5-总结" class="headerlink" title="5. 总结"></a>5. 总结</h1><ul>
<li>优先队列是基于队列 FIFO 先进先出的一种数据结构</li>
<li>优先队列 通过比较器 <code>Comparator</code> 为元素设置优先级，队列内的元素会按优先级的高低排序</li>
<li>优先队列的底层是通过堆排序实现的</li>
<li>除了出队方式遍历以外，其他方式遍历的优先队列结果都将是无序的，只能通过出队的方式才是有序的</li>
<li>优先队列默认是升序，降序的话可以通过<code>Collections.reverseOrder()</code>方法获得一个降序的比较器</li>
<li>继承于 <code>AbstractQueue</code> 类 ，直接实现了 <code>java.io.Serializable</code>接口 表示可序列化，间接实现<code>Queue</code>接口</li>
<li><code>remove()</code>方法<strong>不会</strong>抛异常</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/JavaSE/" class="category-chain-item">JavaSE</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Java/">#Java</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Java集合系列1_ PriorityQueue优先队列 _ 综合运用 _ 深入理解</div>
      <div>http://example.com/2021/11/22/Java集合系列（一）_ PriorityQueue优先队列 _ 综合运用 _ 深入理解/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2021年11月22日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/11/30/MySQL_%20CentOS%E7%B3%BB%E7%BB%9F%E5%AE%89%E8%A3%85MySQL5.7%E7%89%88%E6%9C%AC%20_%20%E9%85%8D%E7%BD%AE%E6%95%99%E7%A8%8B%20_%20%E9%99%84%E5%B8%A6%E8%B5%84%E6%BA%90/" title="Mysql _ CentOS系统安装Mysql5.7版本 _ 配置教程 _ 附带资源">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Mysql _ CentOS系统安装Mysql5.7版本 _ 配置教程 _ 附带资源</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/11/21/Android%20_%20%E5%90%8C%E6%97%B6%E5%AE%9E%E7%8E%B0%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0%E5%92%8C%E4%B8%8B%E6%8B%89%E5%8A%A0%E8%BD%BD%20_%20%E5%9F%BA%E4%BA%8ESwipeRefreshLayout%20%E5%92%8C%20ListView/" title="Android _ 同时实现上拉刷新和下拉加载 _ 基于SwipeRefreshLayout 和 ListView">
                        <span class="hidden-mobile">Android _ 同时实现上拉刷新和下拉加载 _ 基于SwipeRefreshLayout 和 ListView</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
